package Test8;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Demo6 {
    public static void main(String[] args) throws IOException {
        File src=new File("D:\\Test");
        File dest=new File(src.getParentFile(),src.getName()+".zip");
        ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(dest));
        toZip(src,zos,src.getName());
        zos.close();
    }public static void toZip(File src,ZipOutputStream zos,String name) throws IOException {
        File[]files=src.listFiles();
        for (File file:files){
            if (file.isFile()){
                ZipEntry zipEntry=new ZipEntry(name+"\\"+file.getName());
                zos.putNextEntry(zipEntry);
                FileInputStream fis=new FileInputStream(file);
                int b;
                while((b=fis.read())!=-1){
                    zos.write(b);
                }
                zos.closeEntry();
            }else {
                toZip(file,zos,name+"\\"+file.getName());
            }
        }
    }
}
